#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include"mystdio.h"
#include<string.h>
#include<stdlib.h>

mFILE *mfopen(const char *filename, const char *mode)
{
	int fd = -1;
	if(strcmp(mode, "r") == 0)
	{
		fd = open(filename,O_RDONLY);
	}
	else if(strcmp(mode, "w") == 0)
	{
		fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC, 0666);
	}
	else if(strcmp(mode, "a") == 0)
	{
		fd = open(filename,O_CREAT|O_WRONLY|O_APPEND, 0666);
	}

	if(fd < 0)
	{
		return NULL;
	}

	mFILE * file = (mFILE*)malloc(sizeof(mFILE));
	if(file == NULL)
		return NULL;

	file->flag = FLUSH_LINE;
	file->fileno = fd;
	file->cap = SIZE;
	file->size = 0;
	
	return file;
}
void mfflush(mFILE *stream)
{
	if(stream != NULL && stream->size > 0)
	{
		//写入缓冲区
	write(stream->fileno,stream->outbuffer,stream->size);
		fsync(stream->fileno);//刷新到外设
		stream->size = 0;
	}
}
int mfwrite(const void *ptr, int num, mFILE *stream)
{
	memcpy(stream->outbuffer+stream->size,ptr,num);
	stream->size += num;

	if(stream->flag == FLUSH_LINE && 
			stream->outbuffer[stream->size-1] == '\n')
	{
		mfflush(stream);
	}
	
	return num;
}
void mfclose(mFILE *stream)
{
	mfflush(stream);

	close(stream->fileno);
}
